import {
  ADD_COUNTER,
  ADD_TO_CART,
  CHECK_CLICK
} from './mutation-types'

export default {
  // 这里可以解构context为(context,state),即可将context.state直接写成state
  addCart(context, payload) {
    // state.cartList.push(payload);
    // console.log(state.cartList);

    // find：一种断言函数，遍历数组，找到符合条件的立即退出
    // payload为传进来的商品对象
    // let oldProduct = context.state.cartList.find(item => item.iid === payload.iid);
    // if(oldProduct){
    //   oldProduct.counter += 1;
    // }else{
    //   payload.counter = 1;
    //   context.state.cartList.push(payload)
    // }
    return new Promise((resolve, reject) => {
      let oldProduct = context.state.cartList.find(item => item.iid === payload.iid);
      if (oldProduct) {
        context.commit(ADD_COUNTER, oldProduct);
        resolve('当前商品数量+1');
      } else {
        payload.counter = 1;
        context.commit(ADD_TO_CART, payload)
        resolve('添加了新的商品');
      }
    })
  },

  // 修改选中状态
  checkClick(context, payload) {
    context.commit(CHECK_CLICK, payload)
  }
}